import axios from 'axios'
import Qs from 'qs'
import { constant } from '@/plugins/BaseInfo'
import { getToken,removeToken } from '@/utils/TokenOpers'
import { Message } from 'ant-design-vue';

axios.defaults.withCredentials = true // 让ajax携带cookie
axios.defaults.headers = {
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}

// Access-Control-Allow-Origin
const service = axios.create({// 创建 axios 实例
  baseURL: constant.baseUrl,
  timeout: 0 ,// 请求超时时间
  withCredentials: false, // default
})
//request
service.interceptors.request.use(
  request => {
	const token = getToken()
	if (token && token!= undefined)
		request.headers['AUTOSC-TOKEN'] = token
	if (Object.prototype.toString.call(request.data) != '[object FormData]') 
	  request.data = Qs.stringify(request.data)
    return request
  },
  err=>{
    console.log(err)
    return Promise.reject(err.data)
  }
)

//response
service.interceptors.response.use(
  response=> {
    const res = response.data
    if (res.code == 200)
      return res.data.tag === false? Promise.reject(res):Promise.resolve(res)
    else if(res.code){
        let message = '服务器异常'
        switch(res.code){
          case 401: 
            message = '未授权的用户'
            break
          case 403: 
            message = '异常请求'
            break
          case 404: 
            message = '资源未找到'
            break
          case 500: 
            message = '服务器异常'
            break
          case 503: 
            message = '服务器维护中'
            break
          case 1098:
            message = '用户名或密码错误'
            break
          case 1401:
            message = "报文组备注重复、换一个试试吧"
            break
        }
        Message.error(message)
        return Promise.reject(res)
    }else{
      return Promise.resolve(res)
    }
  },
  err=>{
    console.log(err)
    const {status} = JSON.parse(JSON.stringify(err))
    let message = '服务器异常'
    switch(status){
      case 404:
        message = '404 Not Found'
        break
    }
    // removeToken()
    Message.error(message)
    return Promise.reject(err.data)
  }
)


export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    service.post(url, data).then(
      response => {
        resolve(response);
      },
      err => {
        reject(err);
      }
    );
  });
}

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params: params })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export default service